/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.mgt.server.service.power.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.repository.JoinCrudRepository;
import com.google.common.collect.Maps;
import com.iwindplus.boot.domain.enums.BizCodeEnum;
import com.iwindplus.boot.domain.enums.EnableStatusEnum;
import com.iwindplus.boot.domain.exception.BizException;
import com.iwindplus.boot.redis.manager.SerialNumManager;
import com.iwindplus.mgt.domain.constant.MgtConstant;
import com.iwindplus.mgt.domain.dto.power.UserGroupDTO;
import com.iwindplus.mgt.domain.dto.power.UserGroupSaveEditDTO;
import com.iwindplus.mgt.domain.dto.power.UserGroupSearchDTO;
import com.iwindplus.mgt.domain.enums.MgtCodeEnum;
import com.iwindplus.mgt.domain.enums.MgtCodePrefixEnum;
import com.iwindplus.mgt.domain.vo.power.UserGroupBaseCheckedVO;
import com.iwindplus.mgt.domain.vo.power.UserGroupExtendVO;
import com.iwindplus.mgt.domain.vo.power.UserGroupPageVO;
import com.iwindplus.mgt.domain.vo.power.UserGroupVO;
import com.iwindplus.mgt.server.mapper.power.UserGroupMapper;
import com.iwindplus.mgt.server.model.power.UserGroupDO;
import com.iwindplus.mgt.server.service.power.UserGroupRoleService;
import com.iwindplus.mgt.server.service.power.UserGroupService;
import com.iwindplus.mgt.server.service.power.UserGroupUserService;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 组业务层接口实现类.
 *
 * @author zengdegui
 * @since 2019/10/9
 */
@Service
@CacheConfig(cacheNames = {"userGroup"})
@Transactional(rollbackFor = Exception.class)
public class UserGroupServiceImpl extends JoinCrudRepository<UserGroupMapper, UserGroupDO> implements UserGroupService {

    @Resource
    private SerialNumManager serialNumManager;

    @Resource
    private UserGroupUserService userGroupUserService;

    @Resource
    private UserGroupRoleService userGroupRoleService;

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroupRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public boolean save(UserGroupSaveEditDTO entity) {
        entity.setStatus(EnableStatusEnum.ENABLE);
        entity.setBuildInFlag(Boolean.FALSE);
        this.getNameIsExist(entity.getName().trim(), entity.getOrgId());
        if (CharSequenceUtil.isBlank(entity.getCode())) {
            entity.setCode(this.serialNumManager.getSerialNum(MgtCodePrefixEnum.USER_GROUP_PREFIX.getValue()));
        }
        this.getCodeIsExist(entity.getCode().trim(), entity.getOrgId());
        entity.setSeq(this.getNextSeq(entity.getOrgId()));
        final UserGroupDO model = BeanUtil.copyProperties(entity, UserGroupDO.class);
        super.save(model);
        entity.setId(model.getId());
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroupRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public List<UserGroupVO> saveBatchInit(List<UserGroupDTO> entities) {
        List<UserGroupVO> resultList = new ArrayList<>(10);
        AtomicReference<Integer> seq = new AtomicReference<>();
        AtomicBoolean flag = new AtomicBoolean(true);
        List<UserGroupDTO> saveList = new ArrayList<>(10);
        List<UserGroupDTO> existList = new ArrayList<>(10);
        entities.forEach(entity -> {
            final UserGroupDO data = super.getOne(Wrappers.lambdaQuery(UserGroupDO.class)
                .eq(UserGroupDO::getName, entity.getName())
                .eq(UserGroupDO::getOrgId, entity.getOrgId()));
            if (Objects.isNull(data)) {
                if (flag.get()) {
                    seq.set(this.getNextSeq(entity.getOrgId()));
                    flag.set(false);
                }
                entity.setSeq(seq.getAndSet(seq.get() + 1));
                saveList.add(entity);
            } else {
                final UserGroupDTO dto = BeanUtil.copyProperties(data, UserGroupDTO.class);
                existList.add(dto);
            }
        });
        if (CollUtil.isNotEmpty(saveList)) {
            final List<UserGroupDO> doList = BeanUtil.copyToList(saveList, UserGroupDO.class);
            super.saveBatch(doList, DEFAULT_BATCH_SIZE);
            final List<UserGroupVO> voList = BeanUtil.copyToList(doList, UserGroupVO.class);
            resultList.addAll(voList);
        }
        if (CollUtil.isNotEmpty(existList)) {
            final List<UserGroupVO> voList = BeanUtil.copyToList(existList, UserGroupVO.class);
            resultList.addAll(voList);
        }
        return resultList;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroupRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public boolean removeByIds(List<Long> ids) {
        List<UserGroupDO> list = super.listByIds(ids);
        if (CollUtil.isEmpty(list)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        boolean match = list.stream().anyMatch(UserGroupDO::getBuildInFlag);
        if (Boolean.TRUE.equals(match)) {
            throw new BizException(BizCodeEnum.HAS_BUILD_IN_DATA);
        }
        this.userGroupUserService.removeByUserGroupIds(ids);
        this.userGroupRoleService.removeByUserGroupIds(ids);
        super.removeByIds(ids);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroupRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public boolean edit(UserGroupSaveEditDTO entity) {
        // 编辑
        UserGroupDO data = super.getById(entity.getId());
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        // 校验名称是否存在
        if (CharSequenceUtil.isNotBlank(entity.getName()) && !CharSequenceUtil.equals(data.getName(), entity.getName().trim())) {
            this.getNameIsExist(entity.getName().trim(), data.getOrgId());
        }
        if (CharSequenceUtil.isNotBlank(entity.getCode()) && !CharSequenceUtil.equals(data.getCode(), entity.getCode().trim())) {
            this.getCodeIsExist(entity.getCode().trim(), data.getOrgId());
        }
        if (Objects.isNull(entity.getVersion())) {
            entity.setVersion(data.getVersion());
        }
        final UserGroupDO model = BeanUtil.copyProperties(entity, UserGroupDO.class);
        super.updateById(model);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroupRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public boolean editStatus(Long id, EnableStatusEnum status) {
        UserGroupDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (status.equals(data.getStatus())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        UserGroupDO param = new UserGroupDO();
        param.setId(id);
        param.setStatus(status);
        param.setVersion(data.getVersion());
        super.updateById(param);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroupRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public boolean editBuildIn(Long id, Boolean buildInFlag) {
        UserGroupDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (buildInFlag.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        UserGroupDO param = new UserGroupDO();
        param.setId(id);
        param.setBuildInFlag(buildInFlag);
        param.setVersion(data.getVersion());
        super.updateById(param);
        return Boolean.TRUE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"userGroup"}, allEntries = true),
            @CacheEvict(cacheNames = {"userGroupRole"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true),
            @CacheEvict(cacheNames = {"role"}, allEntries = true),
        }
    )
    @Override
    public Map<Long, Long> editInitToOrg(Long orgId, Set<Long> userGroupIds) {
        Map<Long, Long> idMap = Maps.newHashMap();
        if (CollUtil.isEmpty(userGroupIds)) {
            return Collections.emptyMap();
        }
        final List<UserGroupDO> entities = super.list(Wrappers.lambdaQuery(UserGroupDO.class)
            .in(UserGroupDO::getId, userGroupIds).orderByAsc(UserGroupDO::getSeq));
        if (CollUtil.isEmpty(entities)) {
            return Collections.emptyMap();
        }
        final List<UserGroupDO> paramList = BeanUtil.copyToList(entities, UserGroupDO.class);
        this.buildInitList(orgId, paramList);
        final List<UserGroupDTO> dtoList = BeanUtil.copyToList(paramList, UserGroupDTO.class);
        final List<UserGroupVO> voList = this.saveBatchInit(dtoList);
        final List<UserGroupDO> newList = BeanUtil.copyToList(voList, UserGroupDO.class);
        this.buildIdMap(idMap, entities, newList);
        return idMap;
    }

    @Override
    public IPage<UserGroupPageVO> page(UserGroupSearchDTO entity) {
        PageDTO<UserGroupDO> page = new PageDTO<>(entity.getCurrent(), entity.getSize());
        page.setOptimizeCountSql(Boolean.FALSE);
        page.setOptimizeJoinOfCountSql(Boolean.FALSE);
        return super.baseMapper.selectPageByCondition(page, entity);
    }

    @Cacheable(key = "#root.methodName + '_' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public UserGroupExtendVO getDetailExtend(Long id) {
        return super.baseMapper.selectDetailById(id);
    }

    @Cacheable(key = "#root.methodName + '_' + #p0 + '_' + #p1 + '_' + #p2", condition = "#p1 != null", unless = "#result == null")
    @Override
    public List<UserGroupBaseCheckedVO> listByUserId(Long orgId, Long userId) {
        List<UserGroupBaseCheckedVO> allList = super.baseMapper.selectListByOrgId(orgId);
        if (CollUtil.isEmpty(allList)) {
            return null;
        }
        if (Objects.nonNull(userId)) {
            List<UserGroupBaseCheckedVO> checkedList = super.baseMapper.selectListByUserId(orgId, userId);
            if (CollUtil.isNotEmpty(checkedList)) {
                allList = this.listWithChecked(allList, checkedList);
            }
        }
        return allList;
    }

    @Cacheable(key = "#root.methodName + '_' + #p0 + '_' + #p1", condition = "#p0 != null", unless = "#result == null")
    @Override
    public List<UserGroupBaseCheckedVO> listByRoleId(Long orgId, Long roleId) {
        List<UserGroupBaseCheckedVO> allList = super.baseMapper.selectListByOrgId(orgId);
        if (CollUtil.isEmpty(allList)) {
            return null;
        }
        if (Objects.nonNull(roleId)) {
            List<UserGroupBaseCheckedVO> checkedList = super.baseMapper.selectListByRoleId(orgId, roleId);
            if (CollUtil.isNotEmpty(checkedList)) {
                allList = this.listWithChecked(allList, checkedList);
            }
        }
        return allList;
    }

    private void getNameIsExist(String name, Long orgId) {
        QueryWrapper<UserGroupDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserGroupDO::getName, name);
        if (Objects.nonNull(orgId)) {
            queryWrapper.lambda().eq(UserGroupDO::getOrgId, orgId);
        }
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.NAME_EXIST);
        }
    }

    private void getCodeIsExist(String code, Long orgId) {
        QueryWrapper<UserGroupDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserGroupDO::getCode, code);
        queryWrapper.lambda().eq(UserGroupDO::getOrgId, orgId);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.CODE_EXIST);
        }
    }

    /**
     * 查询下一个排序号.
     *
     * @param orgId 组织主键
     * @return Integer
     */
    private Integer getNextSeq(Long orgId) {
        QueryWrapper<UserGroupDO> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(orgId)) {
            queryWrapper.lambda().eq(UserGroupDO::getOrgId, orgId);
        }
        queryWrapper.select("max(seq) as seq");
        Function<Object, Integer> function = val -> Integer.valueOf(val.toString());
        Integer data = super.getObj(queryWrapper, function);
        return Optional.ofNullable(data).map(x -> x + 1).orElse(1);
    }

    private List<UserGroupBaseCheckedVO> listWithChecked(List<UserGroupBaseCheckedVO> allList, List<UserGroupBaseCheckedVO> checkedList) {
        return allList.stream().peek(map -> checkedList.stream()
                .filter(m -> Objects.equals(m.getId(), map.getId())).forEach(m -> map.setChecked(m.getChecked())))
            .collect(Collectors.toCollection(ArrayList::new));
    }

    private void buildInitList(Long orgId, List<UserGroupDO> entities) {
        entities.forEach(entity -> {
            entity.setId(null);
            entity.setVersion(0);
            entity.setOrgId(orgId);
            entity.setRemark(MgtConstant.REMARK_INIT);
        });
    }

    private void buildIdMap(Map<Long, Long> idMap, List<UserGroupDO> oldList, List<UserGroupDO> newList) {
        oldList.forEach(oldData -> newList.forEach(newData -> {
            if (oldData.getName().equals(newData.getName())) {
                idMap.put(oldData.getId(), newData.getId());
            }
        }));
    }
}
